package org.wesc.boot.service.async;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Wesley
 * @date 2021/4/16
 */
@Configuration
public class AsyncEcsConfig {

    /** 核心线程数 */
    @Value("${async.executor.ecs.core-pool-size}")
    private int corePoolSize;

    /** 最大线程数 */
    @Value("${async.executor.ecs.max-pool-size}")
    private int maxPoolSize;

    /** 队列容量 */
    @Value("${async.executor.ecs.queue-capacity}")
    private int queueCapacity;

    /** 线程活跃时间（秒）*/
    @Value("${async.executor.ecs.keep-alive-seconds}")
    private int keepAliveSeconds;

    /** 线程名称前缀 */
    @Value("${async.executor.ecs.name.prefix}")
    private String namePrefix;

    /**
     * 配置线程池
     */
    @Bean(name = "ecsPoolTaskExecutor")
    public ThreadPoolTaskExecutor poolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(namePrefix);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }

}
